package org.extreme.web.plugins.du;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

public class Du {
	
	public static final Du me = new Du();
	
	private DataSource ds;
	private QueryRunner runner;
	private static Map<Class<?>,BeanHandler<?>> beanHandlers = new HashMap<Class<?>,BeanHandler<?>>();
	private static Map<Class<?>,BeanListHandler<?>> beanListHandlers = new HashMap<Class<?>,BeanListHandler<?>>();
	
	public Du(){
	}
	
	public void init(DataSource ds){
		this.ds = ds;
		this.runner = new QueryRunner(ds);
	}
	
	/**
	 * 查询列表
	 * @param sql
	 * @param claz
	 * @return
	 */
	public <T> List<T> query(Class<T> claz,String sql,Object... params){
		try{
			return runner.query(sql, getBeanListHandler(claz),params);
		}catch(Exception e){
			e.printStackTrace();
			throw new DuException();
		}
	}
	
	/**
	 * 查询一个对象
	 * @param sql
	 * @param claz
	 * @return
	 */
	public <T> T queryObj(Class<T> claz,String sql, Object... params){
		try{
			return runner.query(sql,getBeanHandler(claz),params);
		}catch(Exception e){
			e.printStackTrace();
			throw new DuException();
		}
	}
	
	public <T> BeanHandler<T> getBeanHandler(Class<T> claz){
		return new BeanHandler<T>(claz);
	}
	
	@SuppressWarnings("unchecked")
	public <T> BeanListHandler<T> getBeanListHandler(Class<T> claz){
		if(beanListHandlers.containsKey(claz)) return (BeanListHandler<T>) beanListHandlers.get(claz);
		return new BeanListHandler<T>(claz);
	}
}
